/*
 * Copyright (C) 2009 Leandro de Oliveira Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.japa.repository.query.loader.jpa;

import java.util.*;

import javax.persistence.*;

import org.slf4j.*;
import org.springframework.orm.jpa.*;

import com.google.code.japa.annotation.*;
import com.google.code.japa.repository.*;
import com.google.code.japa.repository.collection.*;
import com.google.code.japa.repository.collection.jpa.*;
import com.google.code.japa.repository.query.*;
import com.google.code.japa.repository.query.loader.*;

/**
 * Loader of queries run against a JPA repository.
 * 
 * @author Leandro Aparecido
 * @since 1.0
 * @see com.google.code.japa.repository.query.loader.RepositoryQueryLoader
 */
public class JpaRepositoryQueryLoader implements RepositoryQueryLoader {

	private static final Logger logger = LoggerFactory.getLogger(JpaRepositoryQueryLoader.class);

	/**
	 * Helper to execute JPA operations.
	 */
	private JpaTemplate jpaTemplate;

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> load(RepositoryQueryParameters parameters) {
		if (parameters == null) {
			throw new IllegalArgumentException("Repository query parameters cannot be null");
		}
		
		List<T> list;
		if (parameters.isExtent()) {
			if (parameters.getType() == null) {
				throw new IllegalArgumentException("Type cannot be null when loading extent");
			}
			list = loadExtent(parameters.getType(), parameters.getFetchStrategy(), parameters.getFetchSize());
		} else {
			if (parameters.getQueryName() == null) {
				throw new IllegalArgumentException("Query name cannot be null when loading from query");
			}
			list = loadFromQuery(parameters.getQueryName(), parameters.getParameters());
		}
		
		return list;
	}
	
	/**
	 * Load the extent of an entity.
	 * 
	 * @param <T> Type of the entity.
	 * @param type Class of the entity.
	 * @param fetchStrategy Fetch strategy to use when loading the extent.
	 * @param fetchSize Fetch size for strategies that support/require it.
	 * @return List of entities fetched using the specified strategy.
	 */
	protected <T> List<T> loadExtent(Class<T> type, FetchStrategy fetchStrategy, int fetchSize) {
		logger.debug("Loading extent of [{}]", type.getName());
		PersistentCollectionStrategy<T> strategy = JpaPersistentCollectionStrategyFactory.create(type, getJpaTemplate(), fetchStrategy, fetchSize);
		return new PersistentList<T>(strategy);
	}

	/**
	 * Executes the specified query.
	 * 
	 * @param <T> Type of the entity.
	 * @param queryName Name of the query to execute.
	 * @param parameters Parameters of the query.
	 * @return List of entities returned by the query.
	 */
	@SuppressWarnings("unchecked")
	protected <T> List<T> loadFromQuery(String queryName, Map<String, QueryParameter> parameters) {
		logger.debug("Loading value from query [{}] with parameters {}", queryName, parameters);
		return getJpaTemplate().executeFind(new JpaQueryCallback(queryName, parameters));
	}
	
// Getters/Setters

	public JpaTemplate getJpaTemplate() {
		return jpaTemplate;
	}
	
	public void setJpaTemplate(JpaTemplate jpaTemplate) {
		this.jpaTemplate = jpaTemplate;
	}
	
	public void setEntityManager(EntityManager entityManager) {
		this.jpaTemplate = new JpaTemplate(entityManager);
	}
	
	public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		this.jpaTemplate = new JpaTemplate(entityManagerFactory);
	}
}
